function corrmat = fsb_corr2d(array1,array2)

% FSB: Calculate a correlation matrix from two matrices
%
% EXAMPLE: 
% Rho = fsb_corr2d(idat, hemodynamics(:,1));
%
% INPUT:
% array1,array2: two arbitrary matrices with same length
%
% OUTPUT:
% Rho: Correlation matrix
%
% CALLED BY:
% fsb_calculate_corr.m
% fsb_calculate_full_map.m
%
% NOTES:
% used for accelerating map calculation in
% fsb_calculate_corr.m
% Output is a vector that needs to be reshaped into a matrix
%
% Copyright 2010 MPI for Biological Cybernetics
% Author: Steffen Stoewer
% License: GNU GPL, no express or implied warranties
% 
% $ Revision 1.0
%~~~~~~~~~~~~~~~~~~~~~~~~~~

% Get array size
array_size = size(array1,1);

% Remove means
array1_mc = array1 - repmat(sum(array1,1)/array_size,array_size,1); 
array2_mc = array2 - repmat(sum(array2,1)/array_size,array_size,1);

% Calculate Covariance
array_cov = (array1_mc' * array2_mc) / (array_size-1);

% Calculate STDs
array1_sd = sqrt(sum(array1_mc.^2,1) / (array_size-1)); 
array2_sd = sqrt(sum(array2_mc.^2,1) / (array_size-1));

% Calculate Correlation Matrix
corrmat = array_cov ./ (array1_sd'*array2_sd);

end
